package com.xuxiao.controller;

import com.xuxiao.common.Login;
import com.xuxiao.common.Result;
import com.xuxiao.entrty.UserInfo;
import com.xuxiao.service.UserInfoService;
import com.xuxiao.util.IdentifyCodeUtils;
import com.xuxiao.util.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.util.HashMap;

@Slf4j
@RestController
public class LoginController {
    @Autowired
    private UserInfoService userInfoService;

    @PostMapping("/login")
    public Result login(Login login, HttpSession session) {
        log.info("登录：{}", login);
        System.out.println(login.getCode());
        String sessionCode = (String) session.getAttribute("identifyCode");
        System.out.println(sessionCode);
        if (login.getCode().equalsIgnoreCase(sessionCode)) {
            System.out.println("验证码正确");
            UserInfo userInfo1 = userInfoService.login(login.getUsername(), login.getPassword());
            if (userInfo1 != null) {
                HashMap<String, Object> claims = new HashMap<>();
                claims.put("id", userInfo1.getCustomerID());
                claims.put("name", userInfo1.getUsername());
                String jwt = JWTUtils.generateJWT(claims);
                return Result.success(jwt);
            }
        } else {
            System.out.println("验证码错误");
            return Result.error("验证码错误");
        }
        return Result.error("用户名或密码错误");
    }

    @GetMapping("/checkCode")
    public void identifyImage(HttpServletResponse response, HttpSession session) {
        //创建随机验证码
        IdentifyCodeUtils utils = new IdentifyCodeUtils();
        String identifyCode = utils.getIdentifyCode();
        //session存入验证码
        session.setAttribute("identifyCode", identifyCode);
        //根据验证码创建图片
        BufferedImage identifyImage = utils.getIdentifyImage(identifyCode);
        //回传给前端
        utils.responseIdentifyImg(identifyImage, response);
    }
}
